package com.bungarus.processor;

import com.bungarus.codec.protobuf.MessageProtobuf;
import com.bungarus.model.MessageBuilder;
import com.bungarus.model.MessageProcessException;
import com.bungarus.model.MessageProcessor;
import io.netty.channel.Channel;

/**
 * Send status message to client
 * Created by tang on 2018/12/25.
 */
public class AccessStatusProcessor implements MessageProcessor {
    static private AccessStatusProcessor processor = new AccessStatusProcessor();
    private AccessStatusProcessor() {
    }

    public static AccessStatusProcessor getInstance() {
        return processor;
    }

    @Override
    public void process(MessageProtobuf.Message message, Channel from, Channel to) throws MessageProcessException {
        if(null == to){//Throws away the status message when client is offline and just send ack of status message back to busi
            from.writeAndFlush(MessageBuilder.buildAckMessage(message.getHeader().getId(), message.getHeader().getId2()));
        }
        else {//notify the client the someone's latest status
            to.writeAndFlush(message).addListener(channelFuture -> {
                if (channelFuture.isSuccess()) {
                    //just send ack of status message back to busi
                    //it's not necessary to wait for client's ack.
                    from.writeAndFlush(MessageBuilder.buildAckMessage(message.getHeader().getId(), message.getHeader().getId2()));
                }
            });
        }
    }
}
